package com.advanced.config.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 刘志强
 * @date 2020/8/10 11:36
 * redis分布式锁
 */
@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获得锁 ture 获得锁 false 没有获得锁
     *
     * @param key
     * @param time 过期时间
     * @return
     */
    public Boolean getLock(String key, Long time) {
        // 创建事物 防止命令执行一半
        return stringRedisTemplate.opsForValue().setIfAbsent(key, key, time, TimeUnit.SECONDS);
    }

    /**
     * 释放锁
     *
     * @param key
     */
    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

}
